package com.smzd.utils.httpclient;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.smzd.utils.FileUtil;

public class Response {
    private Request beforeRedirectRequest;
    private Request request;
    private HttpResponse httpResponse;

    public Response() {
    }

    public Response(HttpResponse httpResponse) {
        this.httpResponse = httpResponse;
    }

    private String redirect;
    private Boolean isRedirect;

    public boolean isRedirectResponse() {
        if (isRedirect != null) {
            return isRedirect;
        }
        redirect = null;
        Header[] locationHeaders = httpResponse.getHeaders("Location");
        if (locationHeaders != null && locationHeaders.length > 0) {
            redirect = locationHeaders[0].getValue();
            isRedirect = true;
        } else {
            isRedirect = false;
        }
        return isRedirect;
    }

    public String getRedirectPath() {
        return isRedirectResponse() ? redirect : null;

    }
    
    public void downloadFile(File file) throws IllegalStateException, IOException{
        HttpEntity entity = httpResponse.getEntity();
        InputStream is = entity.getContent();
        FileUtil.downloadFile(is, file);
    }

    public StringBuffer getResponseContent() throws IllegalStateException,
            IOException {
        HttpEntity entity = httpResponse.getEntity();
        InputStream is = entity.getContent();
        StringBuffer sb = FileUtil.readContent(is);
        return sb;
    }

    void consume() {
        try {
            EntityUtils.consume(httpResponse.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Request getBeforeRedirectRequest() {
        return beforeRedirectRequest;
    }

    void setBeforeRedirectRequest(Request request) {
        this.beforeRedirectRequest = request;
    }

    void setRequest(Request request) {
        this.request = request;
    }

    public Request getRequest() {
        return request;
    }
}
